<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件大小计算方法测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .method-section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background: #fafafa;
        }
        .method-title {
            font-size: 18px;
            font-weight: bold;
            color: #409eff;
            margin-bottom: 10px;
        }
        .method-desc {
            color: #666;
            margin-bottom: 15px;
            line-height: 1.5;
        }
        .test-button {
            background: #409eff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s;
        }
        .test-button:hover {
            background: #337ecc;
        }
        .result {
            margin-top: 15px;
            padding: 10px;
            background: #f0f9ff;
            border-left: 4px solid #409eff;
            border-radius: 4px;
            display: none;
        }
        .log {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 15px;
            margin-top: 20px;
            max-height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
        }
        .log-entry {
            margin-bottom: 8px;
            padding: 4px 0;
        }
        .log-info { color: #0066cc; }
        .log-success { color: #28a745; }
        .log-warning { color: #ffc107; }
        .log-error { color: #dc3545; }
    </style>
</head>
<body>
    <div class="container">
        <h1>文件大小计算方法测试</h1>
        
        <div class="method-section">
            <div class="method-title">1. 基于时长估算 (duration)</div>
            <div class="method-desc">
                根据视频时长和比特率估算文件大小。这种方法最准确，但需要M3U8文件包含时长信息。
            </div>
            <button class="test-button" onclick="testDurationMethod()">测试时长估算方法</button>
            <div id="duration-result" class="result"></div>
        </div>

        <div class="method-section">
            <div class="method-title">2. 智能采样 (sampling)</div>
            <div class="method-desc">
                选择开头、中间、结尾的分片进行采样，计算平均大小。平衡了速度和准确性。
            </div>
            <button class="test-button" onclick="testSamplingMethod()">测试智能采样方法</button>
            <div id="sampling-result" class="result"></div>
        </div>

        <div class="method-section">
            <div class="method-title">3. 基于分片数量估算 (estimate)</div>
            <div class="method-desc">
                根据分片数量快速估算文件大小。速度最快，但准确性较低。
            </div>
            <button class="test-button" onclick="testEstimateMethod()">测试分片数量估算方法</button>
            <div id="estimate-result" class="result"></div>
        </div>

        <div class="method-section">
            <div class="method-title">4. 自动选择 (auto)</div>
            <div class="method-desc">
                系统自动选择最佳计算方法，优先使用时长估算，然后智能采样，最后基于分片数量估算。
            </div>
            <button class="test-button" onclick="testAutoMethod()">测试自动选择方法</button>
            <div id="auto-result" class="result"></div>
        </div>

        <div class="log" id="log">
            <div class="log-entry log-info">测试日志将在这里显示...</div>
        </div>
    </div>

    <script>
        // 模拟的测试数据
        const mockSegments = [
            { url: 'http://example.com/segment1.ts', duration: 10, size: 1024000 },
            { url: 'http://example.com/segment2.ts', duration: 10, size: 1056000 },
            { url: 'http://example.com/segment3.ts', duration: 10, size: 998000 },
            { url: 'http://example.com/segment4.ts', duration: 10, size: 1032000 },
            { url: 'http://example.com/segment5.ts', duration: 10, size: 1018000 },
            { url: 'http://example.com/segment6.ts', duration: 10, size: 1044000 },
            { url: 'http://example.com/segment7.ts', duration: 10, size: 1002000 },
            { url: 'http://example.com/segment8.ts', duration: 10, size: 1028000 },
            { url: 'http://example.com/segment9.ts', duration: 10, size: 1036000 },
            { url: 'http://example.com/segment10.ts', duration: 10, size: 1014000 }
        ];

        function log(message, type = 'info') {
            const logContainer = document.getElementById('log');
            const entry = document.createElement('div');
            entry.className = `log-entry log-${type}`;
            entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            logContainer.appendChild(entry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 模拟基于时长估算
        function estimateSizeFromDuration(segments) {
            log('开始基于时长估算文件大小...', 'info');
            
            let totalDuration = 0;
            segments.forEach(segment => {
                if (segment.duration) {
                    totalDuration += segment.duration;
                }
            });
            
            if (totalDuration === 0) {
                log('无法获取时长信息，估算失败', 'error');
                return 0;
            }
            
            // 假设平均比特率为 2Mbps
            const estimatedBitrate = 2 * 1024 * 1024; // 2 Mbps in bits per second
            const estimatedSize = (totalDuration * estimatedBitrate) / 8; // 转换为字节
            
            log(`总时长: ${totalDuration}秒`, 'info');
            log(`估算比特率: 2 Mbps`, 'info');
            log(`估算文件大小: ${formatFileSize(estimatedSize)}`, 'success');
            
            return Math.round(estimatedSize);
        }

        // 模拟智能采样
        function estimateSizeFromSmartSampling(segments) {
            log('开始智能采样估算文件大小...', 'info');
            
            const sampleSize = Math.min(5, Math.max(2, Math.floor(segments.length / 20)));
            const samples = [];
            
            // 智能选择采样点：开头、中间、结尾
            if (segments.length >= 3) {
                samples.push(0);
                samples.push(Math.floor(segments.length / 2));
                samples.push(segments.length - 1);
            } else {
                for (let i = 0; i < segments.length; i++) {
                    samples.push(i);
                }
            }
            
            log(`采样 ${samples.length} 个分片: ${samples.map(i => i + 1).join(', ')}`, 'info');
            
            let totalSize = 0;
            let successCount = 0;
            
            samples.forEach(index => {
                const segment = segments[index];
                if (segment.size) {
                    totalSize += segment.size;
                    successCount++;
                    log(`分片 ${index + 1} 大小: ${formatFileSize(segment.size)}`, 'info');
                }
            });
            
            if (successCount > 0) {
                const averageSize = totalSize / successCount;
                const estimatedTotalSize = Math.round(averageSize * segments.length);
                
                log(`平均分片大小: ${formatFileSize(averageSize)}`, 'info');
                log(`估算总大小: ${formatFileSize(estimatedTotalSize)}`, 'success');
                
                return estimatedTotalSize;
            }
            
            log('采样失败，无法估算文件大小', 'error');
            return 0;
        }

        // 模拟基于分片数量估算
        function estimateSizeFromSegmentCount(segments) {
            log('开始基于分片数量估算文件大小...', 'info');
            
            let estimatedSizePerSegment;
            
            if (segments.length <= 10) {
                estimatedSizePerSegment = 2 * 1024 * 1024; // 2MB per segment
                log('少量分片，使用高质量估算: 2MB/分片', 'info');
            } else if (segments.length <= 50) {
                estimatedSizePerSegment = 1.5 * 1024 * 1024; // 1.5MB per segment
                log('中等数量分片，使用标准质量估算: 1.5MB/分片', 'info');
            } else if (segments.length <= 200) {
                estimatedSizePerSegment = 1024 * 1024; // 1MB per segment
                log('大量分片，使用标准质量估算: 1MB/分片', 'info');
            } else {
                estimatedSizePerSegment = 0.8 * 1024 * 1024; // 800KB per segment
                log('超大量分片，使用低质量估算: 800KB/分片', 'info');
            }
            
            const estimatedTotalSize = Math.round(estimatedSizePerSegment * segments.length);
            
            log(`分片数量: ${segments.length}`, 'info');
            log(`估算总大小: ${formatFileSize(estimatedTotalSize)}`, 'success');
            
            return estimatedTotalSize;
        }

        // 模拟自动选择方法
        function calculateTotalSize(segments, method = 'auto') {
            log(`使用计算方法: ${method}`, 'info');
            
            switch (method) {
                case 'duration':
                    return estimateSizeFromDuration(segments);
                case 'sampling':
                    return estimateSizeFromSmartSampling(segments);
                case 'estimate':
                    return estimateSizeFromSegmentCount(segments);
                case 'auto':
                default:
                    // 自动选择最佳方法
                    let result = estimateSizeFromDuration(segments);
                    if (result > 0) {
                        log('自动选择: 基于时长估算', 'success');
                        return result;
                    }
                    
                    result = estimateSizeFromSmartSampling(segments);
                    if (result > 0) {
                        log('自动选择: 智能采样', 'success');
                        return result;
                    }
                    
                    log('自动选择: 基于分片数量估算', 'success');
                    return estimateSizeFromSegmentCount(segments);
            }
        }

        function testDurationMethod() {
            log('=== 测试基于时长估算方法 ===', 'info');
            const result = calculateTotalSize(mockSegments, 'duration');
            document.getElementById('duration-result').innerHTML = `
                <strong>结果:</strong> ${formatFileSize(result)}<br>
                <small>基于 ${mockSegments.length} 个分片，总时长 ${mockSegments.reduce((sum, s) => sum + (s.duration || 0), 0)} 秒</small>
            `;
            document.getElementById('duration-result').style.display = 'block';
        }

        function testSamplingMethod() {
            log('=== 测试智能采样方法 ===', 'info');
            const result = calculateTotalSize(mockSegments, 'sampling');
            document.getElementById('sampling-result').innerHTML = `
                <strong>结果:</strong> ${formatFileSize(result)}<br>
                <small>基于 ${mockSegments.length} 个分片的智能采样</small>
            `;
            document.getElementById('sampling-result').style.display = 'block';
        }

        function testEstimateMethod() {
            log('=== 测试基于分片数量估算方法 ===', 'info');
            const result = calculateTotalSize(mockSegments, 'estimate');
            document.getElementById('estimate-result').innerHTML = `
                <strong>结果:</strong> ${formatFileSize(result)}<br>
                <small>基于 ${mockSegments.length} 个分片的数量估算</small>
            `;
            document.getElementById('estimate-result').style.display = 'block';
        }

        function testAutoMethod() {
            log('=== 测试自动选择方法 ===', 'info');
            const result = calculateTotalSize(mockSegments, 'auto');
            document.getElementById('auto-result').innerHTML = `
                <strong>结果:</strong> ${formatFileSize(result)}<br>
                <small>系统自动选择最佳计算方法</small>
            `;
            document.getElementById('auto-result').style.display = 'block';
        }

        // 页面加载时显示初始信息
        window.onload = function() {
            log('文件大小计算方法测试页面已加载', 'info');
            log(`测试数据: ${mockSegments.length} 个分片`, 'info');
            log('点击上方按钮测试不同的计算方法', 'info');
        };
    </script>
</body>
</html>
